﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Text.RegularExpressions;

namespace SetProxy
{
    public partial class SetProxyForm : Form
    {
        public SetProxyForm()
        {
            InitializeComponent();
        }
        private static string ID = "";
        private void SetProxyBtn_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = ProxySetting.SetProxy(textBox1.Text);
                if (result)
                {
                    MessageBox.Show("设置成功");
                }
                else
                {
                    MessageBox.Show("设置失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置失败,失败原因：" + ex.ToString());
            }
        }
        /// <summary>
        /// 取消代理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UnSetProxyBtn_Click(object sender, EventArgs e)
        {
            try
            {
                bool result = ProxySetting.UnsetProxy();
                if (result)
                {
                    MessageBox.Show("设置成功");
                }
                else
                {
                    MessageBox.Show("设置失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置失败,失败原因：" + ex.ToString());
            }

        }

        private void ChangeProxyBtn_Click(object sender, EventArgs e)
        {

            ProxySetting.UnsetProxy();

            WebClient wc = new WebClient();
            try
            {
                string ProxyUrl = ConfigurationManager.AppSettings["ProxyUrl"];
                string content = wc.DownloadString(ProxyUrl + "/home/getrandomip?count=1");
                Match match = Regex.Match(content, "id\":(?<id>[\\s\\S]*?),\"ip\":\"(?<ip>[\\s\\S]*?)\",\"port\":\"(?<port>[\\s\\S]*?)\"");
                ID = match.Groups["id"].Value;
                wc.DownloadStringAsync(new Uri(ProxyUrl + "/home/NotValidIP?ip=" + ID));
                string ip = match.Groups["ip"].Value + ":" + match.Groups["port"].Value;
                textBox1.Text = ip;
                bool result = ProxySetting.SetProxy(ip);
                //if (result)
                //{
                //    //MessageBox.Show("设置成功");
                //}
                //else
                //{
                //    MessageBox.Show("设置失败");
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show("设置失败,失败原因：" + ex.ToString());
            }
        }
    }
}
